package voloshyn.paliy.ui;

import voloshyn.paliy.arduino.Caterpillar2;
import voloshyn.paliy.arduino.R;
import voloshyn.paliy.connection.ArduinoConnectService;
import voloshyn.paliy.connection.OnConnectListener;
import voloshyn.paliy.connection.VideoStreamingService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

public class ControlActivity extends Activity implements OnClickListener {
    
    private static final String TAG = ControlActivity.class.getName();
    private ArduinoConnectService connectionWithArduino;
    private VideoStreamingService connectWithCamera;

    private TextView textViewInputData;
    private JoystickView joystickView;
    private ImageView imageView;
    private RelativeLayout layoutRoot;
    private ArrayAdapter<String> adapter;
    private BroadcastReceiver receiver;

    private ToggleButton toggleButtonMotionDetection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		WindowManager.LayoutParams.FLAG_FULLSCREEN);
	setContentView(R.layout.control_activity);
	adapter = new ArrayAdapter<String>(this,
		android.R.layout.select_dialog_singlechoice);
	initViews();
    }

    @Override
    protected void onResume() {
	super.onResume();
	initReceiver();
	initArduinoConnection();
    }

    @Override
    protected void onPause() {
	super.onPause();
	unregisterReceiver(receiver);
	closeBluetoothConnections();
    }

    private void closeBluetoothConnections() {
	if (connectWithCamera != null && connectWithCamera.isConnected()) {
	    connectWithCamera.disconnect();
	}

	if (connectionWithArduino.isConnected()) {
	    connectionWithArduino.disconnect();
	}
    }

    private void initViews() {
	layoutRoot = (RelativeLayout) findViewById(R.id.layoutRoot);
	textViewInputData = (TextView) findViewById(R.id.textViewInputData);
	imageView = (ImageView) findViewById(R.id.imageView);
	imageView.setOnClickListener(this);
	toggleButtonMotionDetection = (ToggleButton) findViewById(R.id.toggleButtonMotionDetection);
	toggleButtonMotionDetection
		.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		    @Override
		    public void onCheckedChanged(CompoundButton buttonView,
			    boolean isChecked) {
			layoutRoot.setBackgroundColor(Color.BLUE);
			if (connectWithCamera != null
				&& connectWithCamera.isConnected()) {
			    connectWithCamera.setDetection(isChecked,
				    new Handler.Callback() {
					@Override
					public boolean handleMessage(Message msg) {
					    Boolean isDetected=(Boolean) msg.obj;
					    if(isDetected)
					    {
						layoutRoot.setBackgroundColor(Color.RED);
					    }
					    else
					    {
						layoutRoot.setBackgroundColor(Color.BLUE);
					    }
					    return false;
					}
				    });
			}
			joystickView.setEnabled(!isChecked);
			
		    }
		});
	joystickView = (JoystickView) findViewById(R.id.joystickView);
	joystickView.setOnJoystickListener(new OnJoystickListener() {
	    @Override
	    public void onJoystickPosition(int x, int y) {
		Caterpillar2 iterCaterpillar = Caterpillar2
			.getCaterpillar(x, y);
		if (x != 0 && y != 0) {
		    connectionWithArduino.sendMessage(iterCaterpillar
			    .toString());
		    Log.i(TAG, iterCaterpillar.toString());
		}
	    }
	}, 200);
    }

    private void initArduinoConnection() {
	Bundle extras = getIntent().getExtras();
	String arduinoAddress = extras
		.getString(getString(R.string.mac_address));

	connectionWithArduino = new ArduinoConnectService(arduinoAddress);
	connectionWithArduino.setOnConnectListener(new OnConnectListener() {

	    @Override
	    public void inputData(String theData) {
		Log.i(TAG, "[inputData] data:" + theData);
		theData = theData.replace("><", "\n").replace("{", "")
			.replace("}", "").replace("<", "").replace(">", "");
		textViewInputData.setText(theData);
	    }

	    @Override
	    public void disconnected() {
		Log.i(TAG, "[disconnected]!!!");
		finish();
	    }

	    @Override
	    public void inputData(Bitmap theBitmap) {
	    }
	});
	connectionWithArduino.start();
    }

    @Override
    public void onClick(View v) {
	if (v == imageView) {
	    if (connectWithCamera == null || !connectWithCamera.isConnected()) {
		BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
		onCreateDialog(0).show();
		BluetoothAdapter.getDefaultAdapter().startDiscovery();
	    }
	}
    }

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Devices:");
		adapter.clear();
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String device = adapter.getItem(which);
				String[] array = device.split("\t");
				String cameraMAC = array[array.length - 1];
				BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
				connectWithCamera = new VideoStreamingService(cameraMAC, ControlActivity.this);
				connectWithCamera.setOnConnectListener(new OnConnectListener() {
					@Override
					public void inputData(Bitmap theBitmap) {
						imageView.setImageBitmap(theBitmap);
					}

		    @Override
		    public void inputData(String theData) {
		    }

		    @Override
		    public void disconnected() {
			imageView
				.setImageResource(R.drawable.camera_not_available);
			connectWithCamera = null;
		    }
		});
		connectWithCamera.start();
	    }
	});
	return builder.create();
    }

    private void initReceiver() {
	receiver = new BluetoothScanDevices(adapter);
	registerReceiver(receiver, new IntentFilter(
		BluetoothDevice.ACTION_FOUND));
    }

}
